package com.keeping.aiimagery.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keeping.aiimagery.entity.ChatRoom;
import com.keeping.aiimagery.mapper.ChatRoomMapper;
import com.keeping.aiimagery.service.ChatRoomService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created By Ranger on 2023/4/4.
 */
@Service
public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> implements ChatRoomService {
    
    @Override
    public List<ChatRoom> getRoomByUserId(Long userId) {
        List<ChatRoom> list = new LambdaQueryChainWrapper<>(baseMapper).eq(ChatRoom::getCreatedBy, userId)
                .orderByDesc(ChatRoom::getModifyTime).list();
        if(CollectionUtils.isEmpty(list)){
            ChatRoom build = ChatRoom.builder().roomName("新会话").build();
            this.save(build);
            list.add(build);
        }
        return list;
    }

    @Override
    public boolean saveRoom(String id, String userId, String roomName) {
        ChatRoom one = this.getById(Long.valueOf(id));
        if(one == null){
            if(roomName.length() > 10){
                roomName.substring(0,10);
            }
            ChatRoom chatRoom = new ChatRoom();
            chatRoom.setId(Long.valueOf(id));
            chatRoom.setRoomName(roomName);
            chatRoom.setCreatedBy(Long.valueOf(userId));
            chatRoom.setCreatedTime(LocalDateTime.now());
            chatRoom.setModifyBy(Long.valueOf(userId));
            chatRoom.setModifyTime(LocalDateTime.now());
            chatRoom.setVersion(0L);
            chatRoom.setDeleted(0);
            this.baseMapper.insert(chatRoom);
        }
        return true;
    }

    @Override
    public void delRoomById(String roomId) {
        this.removeById(Long.valueOf(roomId));
    }

    @Override
    public void modifyRoomById(String roomId, String roomName) {
        new LambdaUpdateChainWrapper<>(baseMapper)
                .set(ChatRoom::getRoomName,roomName)
                .eq(ChatRoom::getId,Long.valueOf(roomId))
                .update();
    }
}
